using System;
using System.Drawing;
using System.Globalization;

namespace com.exceptionalsoftware.spacetime.KML
{
    public class KMLColor
    {
        private Color internalColor;

        public KMLColor()
        {
            this.initialize("ffffffff");
        }

        public KMLColor(string kmlColor)
        {
            this.initialize(kmlColor);
        }

        public KMLColor(byte[] abgr)
        {
            this.initialize(abgr);
        }

        public KMLColor(Color c)
        {
            this.internalColor = this.copy(c);
        }

        private void initialize(string kmlColor)
        {
            int kmlColorValue = int.Parse(kmlColor, NumberStyles.HexNumber);

            byte[] components = new byte[4];
            components[3] = (byte)(kmlColorValue & 0xff);
            components[2] = (byte)((kmlColorValue >> 8) & 0xff);
            components[1] = (byte)((kmlColorValue >> 16) & 0xff);
            components[0] = (byte)(kmlColorValue >> 24);

            this.initialize(components);
        }

        private void initialize(byte[] abgr)
        {
            this.internalColor = Color.FromArgb(255, 255, 255, 255);
            if (abgr != null)
            {
                if (abgr.Length == 4)
                {
                    this.internalColor = Color.FromArgb(abgr[0], abgr[3], abgr[2], abgr[1]);
                }
            }
        }

        public byte[] Components
        {
            get { return this.ToByteArray(); }
            set { this.initialize(value); }
        }

        public string KMLFormat
        {
            get { return this.ToString(); }
            set { this.initialize(value); }
        }

        public Color Color
        {
            get { return this.copy(this.internalColor); }
            set { this.internalColor = this.copy(value); }
        }

        private Color copy(Color c)
        {
            return Color.FromArgb(c.ToArgb());
        }

        public override string ToString()
        {
            string alpha = this.internalColor.A.ToString("x2");
            string blue = this.internalColor.B.ToString("x2");
            string green = this.internalColor.G.ToString("x2");
            string red = this.internalColor.R.ToString("x2");

            return alpha + blue + green + red;
        }

        public byte[] ToByteArray()
        {
            byte[] components = new byte[4];
            components[0] = this.internalColor.A;
            components[1] = this.internalColor.B;
            components[2] = this.internalColor.G;
            components[3] = this.internalColor.R;

            return components;
        }

    }

}